"""
管理后台 - 认证接口
"""
from datetime import datetime, timedelta
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.dependencies import get_db, get_current_user
from app.schemas.user import UserLogin, TokenResponse, UserResponse
from app.schemas.common import ResponseModel
from app.crud import user as crud_user
from app.core.security import create_access_token, create_refresh_token
from app.config import settings


router = APIRouter()


@router.post("/login", response_model=ResponseModel)
async def login(
    user_in: UserLogin,
    db: AsyncSession = Depends(get_db)
):
    """
    管理员登录
    
    - **username**: 用户名
    - **password**: 密码
    """
    # 认证用户
    user = await crud_user.user.authenticate(
        db,
        username=user_in.username,
        password=user_in.password
    )
    
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误"
        )
    
    if user.status != 1:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="用户已被禁用"
        )
    
    # 更新最后登录时间
    await crud_user.user.update(
        db,
        db_obj=user,
        obj_in={"last_login_time": datetime.now()}
    )
    
    # 生成Token
    access_token = create_access_token(data={"sub": str(user.id)})
    refresh_token = create_refresh_token(data={"sub": str(user.id)})
    
    return ResponseModel(
        data=TokenResponse(
            access_token=access_token,
            refresh_token=refresh_token
        )
    )


@router.post("/logout", response_model=ResponseModel)
async def logout(current_user = Depends(get_current_user)):
    """
    管理员登出
    """
    # 实际项目中，可以将Token加入黑名单
    return ResponseModel(message="登出成功")


@router.get("/profile", response_model=ResponseModel)
async def get_profile(current_user = Depends(get_current_user)):
    """
    获取当前用户信息
    """
    return ResponseModel(
        data=UserResponse.model_validate(current_user)
    )


@router.post("/refresh", response_model=ResponseModel)
async def refresh_token(
    refresh_token: str,
    db: AsyncSession = Depends(get_db)
):
    """
    刷新Token
    """
    from app.core.security import verify_token
    
    # 验证刷新Token
    payload = verify_token(refresh_token)
    if not payload or payload.get("type") != "refresh":
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="无效的刷新Token"
        )
    
    user_id = payload.get("sub")
    user = await crud_user.user.get_by_id(db, id=user_id)
    
    if not user or user.status != 1:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户不存在或已被禁用"
        )
    
    # 生成新Token
    access_token = create_access_token(data={"sub": user.id})
    new_refresh_token = create_refresh_token(data={"sub": user.id})
    
    return ResponseModel(
        data=TokenResponse(
            access_token=access_token,
            refresh_token=new_refresh_token
        )
    )

